<?php

Loader::using("Models::Entities::Usuarios");

/**
 * Description of AdministrarUsuarios
 *
 * @author JeyDotC
 * 
 * @export Modules
 * @export-metadata RequiredRoles:Agencia
 */
class AdministrarUsuarios extends Module {

    private $roles;

    public function index() {

        $this->assign("usuarios", $this->components->Usuarios->getUsuarios($this->currentUser->getName(), $this->currentUser->getCredential()));

        $this->display("index");
    }

    public function view($id = null) {
        $user = $id != null ? $id : $this->request->get("id");

        if ($this->checkUser($user)) {
            $rolesDisponibles = $this->components->Usuarios->getRolesDisponibles();
            $this->roles = $this->components->Usuarios->getRoles($user);
            if ($this->roles) {
                $rolesDisponibles = array_filter($rolesDisponibles, array($this, 'filterRoles'));
            }

            $this->assign("action", $this->route->action("addRol", array("id" => $user,)));
            $this->assign("removeRoleAction", $this->route->action("quitarRol"));
            $this->assign("removeAction", $this->route->action("remove", array("id" => $user,)));
            $this->assign("rolesDisponibles", $rolesDisponibles);
            $this->assign("user", $user);
            $this->assign("roles", $this->components->Usuarios->getRoles($user));

            $this->display("view");
        } else {
            $this->addMessage(new Message(
                            "Es posible que haya sido eliminado, recargue a p&aacute;gina si lo ve en la lista de usuarios.",
                            "El usuario '$user' no existe",
                            Message::WARNING
            ));
            $this->index();
        }
    }

    public function addRol() {
        if ($this->request->submitted()) {
            $idRol = $this->request->post("idRol");
            $user = $this->request->post("id");

            $this->components->Usuarios->agregarRol($user, $idRol);
        }
        $this->view();
    }

    public function quitarRol() {
        if ($this->request->submitted()) {
            $idRol = $this->request->post("idRol");
            $user = $this->request->post("id");

            $this->components->Usuarios->quitarRol($user, $idRol);
        }
        $this->view();
    }

    public function create() {
        $this->assign("action", $this->route->action("save"));
        $this->assign("usernameCheck", $this->route->action("usernameCheck"));

        $this->display("create");
    }

    public function save() {
        if ($this->request->submitted()) {
            $usuario = new Usuarios();

            $userName = $this->request->post("userName");
            $password = $this->request->post("newPass");
            $passwordConfirm = $this->request->post("newPassConfirm");
            $save = true;

            if ($this->checkUser($userName)) {
                $this->addMessage(new Message("El nombre de usuario '$userName' ya existe, utilice otro nombre.", "El usuario ya existe", Message::ERROR));
                $save = false;
            }

            if ($password != $passwordConfirm) {
                $this->addMessage(new Message("", "Las claves deben coincidir", Message::ERROR));
                $save = false;
            }

            if ($save) {
                $usuario->setUserName($userName);
                $usuario->setPassword(md5($password));
                $save = $this->components->Usuarios->agregarUsuario($usuario);
            }

            if ($save) {
                $this->addMessage(new Message("Por favor, agregue los roles que le corresponden al nuevo usuario, puede editarlos posteriormente.", "Usuario agregado exitosamente", Message::SUCCESS));
                $this->view($userName);
            } else {
                $this->create();
            }
        } else {
            $this->create();
        }
    }

    public function usernameCheck() {
        $user = $this->request->post("user");
        echo $this->checkUser($user) ? "true" : "false";
    }

    public function remove() {
        $id = $this->request->post("id");
        if ($id != $this->currentUser->getName()) {
            $result = $this->components->Usuarios->eliminarUsuario($id);
            if ($result) {
                $this->addMessage(new Message("", "Usuario eliminado exitosamente", Message::SUCCESS));
            }else{
                $this->addMessage(new Message("", "El usuario no pudo ser eliminado", Message::SUCCESS));
            }
        } else {
            $this->addMessage(new Message("¡No puedes eliminar tu propio usuario!", "No se pudo eliminar el usuario", Message::WARNING));
        }

        $this->index();
    }

    private function checkUser($user) {
        $users = $this->components->Usuarios->getUsuarios($this->currentUser->getName(), $this->currentUser->getCredential());
        $users[] = $this->currentUser->getName();
        return in_array($user, $users);
    }

    /**
     *
     * @param Roles $rol 
     */
    private function filterRoles($rol) {
        $result = true;
        foreach ($this->roles as /* @var $rolesDisponibles Roles */$rolUsuario) {
            if ($rolUsuario->getIdRol() == $rol->getIdRol()) {
                $result = false;
                break;
            }
        }

        return $result;
    }

}

?>
